import { useDateListRefs } from "@/components/Overlay/components/DatePicker/useDateList";
import useNumbers from "@/components/Overlay/hooks/useNumbers";
import useVibrate from "@/components/Overlay/hooks/useVibrate";
import { formatDateTime } from "@/views/drawHist/hooks/useUtils";

const showScanRes = ref(false);
const scanNum = ref<string>("");
const scanYear = ref<string>("");
const scanDraw = ref<string>("");
const scanSet = ref<string>("");
const photoData = ref<string>("");
const scanner = ref<any>(null);
export default function useNavigation() {
  const router = useRouter();
  const { dayjs } = useDayjs();
  const { addNumber } = useNumbers();
  const { dateList, curDate } = useDateListRefs();
  const { start } = useVibrate();
  function capturePhoto(scanner: any): string | null {
    if (scanner.value) {
      const videoElement = scanner.value.$el.querySelector("video");
      const canvas = document.createElement("canvas");
      canvas.width = videoElement.videoWidth;
      canvas.height = videoElement.videoHeight;
      const context = canvas.getContext("2d");
      if (context) {
        context.drawImage(videoElement, 0, 0);
        return canvas.toDataURL("image/jpeg");
      }
    }
    return null;
  }
  const navigateToCheckResult = (code: string) => {
    try {
      const [year, draw, set, num] = unref(code)?.split("-") ?? [];
      showScanRes.value = true;
      scanNum.value = num;
      scanYear.value = year;
      scanDraw.value = draw;
      scanSet.value = set;

      const photo = capturePhoto(scanner);
      if (photo) {
        photoData.value = photo;
      }
      start(200);
    } catch (e) {}
  };

  function resetScan() {
    scanNum.value = "";
    scanYear.value = "";
    scanDraw.value = "";
    scanSet.value = "";
    photoData.value = "";
  }

  function closeScanRes() {
    resetScan();
    showScanRes.value = false;
  }
  function setCurDate() {
    curDate.value =
      unref(dateList)?.find?.(it => {
        return (
          String(formatDateTime(it?.draw_date)?.year)?.slice?.(2) ===
          scanYear.value + ""
        );
      })?.draw_date ?? formatDateTime(dayjs().format("YYYY-MM-DD")).ymd;
  }
  function handleAddAndExit() {
    try {
      addNumber(scanNum.value);
      setCurDate();
      closeScanRes();
      router.back();
    } catch (e) {}
  }
  function handleAddAndContinue() {
    addNumber(scanNum.value);
    setCurDate();
    closeScanRes();
    router.replace("/scan?_ts=" + Date.now());
  }

  return {
    navigateToCheckResult,
    showScanRes,
    scanNum,
    closeScanRes,
    handleAddAndExit,
    handleAddAndContinue,
    scanYear,
    scanDraw,
    scanSet,
    resetScan,
    scanner,
    photoData
  };
}
